//
//  PywUploadAccountLoginTimeLong.m
//  PywSdk
//
//  Created by Ampaw on 2017/6/15.
//  Copyright © 2017年 Jade. All rights reserved.
//

#import "PywUploadAccountLoginTimeLong.h"
#import "PywPlatformMain.h"

#define accountLoginLongPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"AccountLoginTimeLong"]

@implementation PywUploadAccountLoginTimeLong

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.account forKey:@"account"];
    [aCoder encodeObject:self.startTime forKey:@"startTime"];
    [aCoder encodeObject:self.endTime forKey:@"endTime"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self.account = [aDecoder decodeObjectForKey:@"account"];
    self.startTime = [aDecoder decodeObjectForKey:@"startTime"];
    self.endTime = [aDecoder decodeObjectForKey:@"endTime"];
    return self;
}

/**
 *  保存单个账号登录时长
 */
+ (void)saveAccountLoginLong:(PywUploadAccountLoginTimeLong *)loginLong
{
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:accountLoginLongPath];
    NSMutableArray *loginLongs = [NSMutableArray arrayWithArray:array];
    
    if (loginLongs.count > 0
        && [loginLong.account isEqualToString:[PywPlatformMain sharedPlatformMain].account]
        && [loginLong.startTime isEqualToString:[PywPlatformMain sharedPlatformMain].startTime]) {
        
        [loginLongs setObject:loginLong atIndexedSubscript:0];
    }else{
        [loginLongs addObject:loginLong];
    }
    
    [NSKeyedArchiver archiveRootObject:loginLongs toFile:accountLoginLongPath];
}

/**
 *  根据游戏账号删除数据
 */
+ (void)removeAccountLoginLong:(NSString *)account
{
    if (account.length == 0) {
        return;
    }
    @try {
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:accountLoginLongPath];
        NSMutableArray *loginLongs = [NSMutableArray arrayWithArray:array];
        
        for (NSInteger i = 0; i < loginLongs.count; i ++) {
            PywUploadAccountLoginTimeLong *loginLong = [loginLongs objectAtIndex:i];
            if ([loginLong.account isEqualToString:account]) {
                [loginLongs removeObjectAtIndex:i];
            }
        }
        [NSKeyedArchiver archiveRootObject:loginLongs toFile:accountLoginLongPath];
    } @catch (NSException *exception) {
        PLog(@"删除失败");
    } @finally {
        
    }
}

/**
 *  返回账号登录时长数组
 */
+ (NSArray *)accountLoginLongs
{
    return [NSKeyedUnarchiver unarchiveObjectWithFile:accountLoginLongPath];
}

@end
